const { app, core, action } = require("photoshop");
const fs = require("uxp").storage.localFileSystem;
const batchPlay = action.batchPlay;
const executeAsModal = core.executeAsModal;

const makeDefaultDocument = async () => {
  const result = await batchPlay(
    [
      {
        _obj: "make",
        new: {
          _obj: "document",
          artboard: false,
          autoPromoteBackgroundLayer: false,
          preset: "Default Photoshop Size",
        },
      },
    ],
    {}
  );

  return result[0];
};

const makeNewLayer = async (id) => {
  const result = await batchPlay(
    [
      {
        _obj: "make",
        _target: [
          {
            _ref: "layer",
          },
        ],
        layerID: id,
      },
    ],
    {}
  );

  return result[0];
};

const convertToSmartObject = async (docId, layerId) => {
  return await batchPlay([{ _obj: "newPlacedLayer" }], {});
};

const openSmartObject = async (layerId) => {
  const result = await batchPlay(
    [
      {
        _obj: "placedLayerEditContents",
        layerID: layerId,
      },
    ],
    {}
  );

  return result[0];
};

const makeSolidColour = async (red, green, blue) => {
  const result = await batchPlay(
    [
      {
        _obj: "make",
        _target: [
          {
            _ref: "contentLayer",
          },
        ],
        using: {
          _obj: "contentLayer",
          type: {
            _obj: "solidColorLayer",
            color: {
              _obj: "RGBColor",
              red: red,
              grain: green,
              blue: blue,
            },
          },
        },
      },
    ],
    {}
  );

  return result[0];
};

const updateSmartObjectLink = async (id, layerId) => {
  const result = await batchPlay(
    [
      {
        _obj: "placedLayerUpdateAllModified",
        documentID: id,
        layerIDs: [layerId],
      },
    ],
    {}
  );

  return result;
};

const saveDocument = async (id, filename, folder) => {
  // Create file
  const file = await folder.createFile(filename, {
    overwrite: true,
  });

  // Generate token
  const token = await fs.createSessionToken(file);

  const result = await batchPlay(
    [
      {
        _obj: "save",
        in: {
          _path: token,
          _kind: "local",
        },
        saveStage: {
          _enum: "saveStageType",
          _value: "saveBegin",
        },
        documentID: id,
      },
    ],
    {}
  );

  return result;
};

const closeDocument = async (id) => {
  const result = await batchPlay(
    [
      {
        _obj: "close",
        saving: {
          _enum: "yesNo",
          _value: "no",
        },
        documentID: id,
      },
    ],
    {}
  );

  return result;
};

const activateDocument = (id) => {
  app.activeDocument = app.documents.find((doc) => doc.id === id);
};

const makeAndOpenSmartObject = async (masterDocId) => {
  // Make new layer
  const newLayer = await makeNewLayer(masterDocId);

  // Convert new layer to smart object
  await convertToSmartObject(masterDocId, newLayer.layerID);

  // Open smart object
  const smartObjectDoc = await openSmartObject(newLayer.layerID);

  return {
    newLayer,
    smartObjectDoc,
  };
};

const main = async () => {
  await executeAsModal(async () => {
    try {
      // Get folder for saving
      const saveFolder = await fs.getFolder();

      // Make master document
      const masterDoc = await makeDefaultDocument();

      // Make and open smart object
      const { newLayer, smartObjectDoc } = await makeAndOpenSmartObject(
        masterDoc.documentID
      );

      // Perform edit to smart object
      await makeSolidColour(0, 0, 255);

      // Generate filename from layer id
      const filename = `SmartObject_${newLayer.layerID}`;

      // Update master doc
      await updateSmartObjectLink(masterDoc.documentID, newLayer.layerID);

      // Save smart object
      await saveDocument(smartObjectDoc.documentID, filename, saveFolder);

      // Close smart object
      await closeDocument(smartObjectDoc.documentID);

      // Activate master document
      activateDocument(masterDoc.documentID);
    } catch (error) {
      console.log("💥", error);
    }
  });
};

//=======
const { app, core } = require("photoshop");
const batchPlay = require("photoshop").action.batchPlay;
const lfs = require("uxp").storage.localFileSystem;

try {
  // Helper functions
  const getParentFolderEntry = async (filepath) => {
    const folderPath = path.dirname(filepath);
    return await lfs.getEntryWithUrl(folderPath);
  };

  const getAnimationFrameCount = async () => {
    return await batchPlay(
      [
        {
          _obj: "get",
          _target: [
            {
              _property: "frameCount",
            },
            {
              _ref: "animationClass",
              _enum: "ordinal",
              _value: "targetEnum",
            },
          ],
          _options: {
            dialogOptions: "dontDisplay",
          },
        },
      ],
      {}
    );
  };

  const selectAnimationFrame = async (index) => {
    return await batchPlay(
      [
        {
          _obj: "select",
          _target: [
            {
              _ref: "animationFrameClass",
              _index: index,
            },
          ],
          _options: {
            dialogOptions: "dontDisplay",
          },
        },
      ],
      {}
    );
  };

  const makeSnapshot = async (name) => {
    return batchPlay(
      [
        {
          _obj: "make",
          _target: [
            {
              _ref: "snapshotClass",
            },
          ],
          from: {
            _ref: "historyState",
            _property: "currentHistoryState",
          },
          name: name,
          using: {
            _enum: "historyState",
            _value: "fullDocument",
          },
          _isCommand: true,
          _options: {},
        },
      ],
      {}
    );
  };

  const revertToSnapshot = async (name) => {
    return batchPlay(
      [
        {
          _obj: "select",
          _target: [
            {
              _ref: "snapshotClass",
              _name: name,
            },
          ],
          _isCommand: true,
          _options: {
            dialogOptions: "dontDisplay",
          },
        },
      ],
      {}
    );
  };

  const deleteSnapshot = async (name) => {
    return batchPlay(
      [
        {
          _obj: "delete",
          _target: [
            {
              _ref: "historyState",
              _name: name,
            },
          ],
          _isCommand: true,
          _options: {
            dialogOptions: "dontDisplay",
          },
        },
      ],
      {}
    );
  };

  const saveJPEG = async (saveFolder, newFilename, quality) => {
    try {
      const doc = app.activeDocument;
      const theNewFile = await saveFolder.createFile(newFilename, {
        overwrite: true,
      });
      const saveFile = await lfs.createSessionToken(theNewFile);
      return batchPlay(
        [
          {
            _obj: "save",
            as: {
              _obj: "JPEG",
              extendedQuality: quality,
              matteColor: {
                _enum: "matteColor",
                _value: "none",
              },
            },
            in: {
              _path: saveFile,
              _kind: "local",
            },
            documentID: doc.id,
            lowerCase: true,
            saveStage: {
              _enum: "saveStageType",
              _value: "saveBegin",
            },
            _isCommand: true,
            _options: {
              dialogOptions: "dontDisplay",
            },
          },
        ],
        {}
      );
    } catch (error) {
      console.log(error);
    }
  };

  // Main process
  await core.executeAsModal(async () => {
    const file = await lfs.getFileForOpening();
    const saveFolder = await getParentFolderEntry(file.nativePath);
    await app.open(file);
    const doc = app.activeDocument;
    const baseFilename = doc.name.slice(0, doc.name.lastIndexOf("."));

    const countFrames = await getAnimationFrameCount();

    const frameCount = countFrames[0].frameCount;

    for (let i = 0; i < frameCount; i++) {
      const newFilename = `${baseFilename}_${i + 1}`;

      await selectAnimationFrame(i + 1);

      await makeSnapshot(newFilename);

      doc.flatten();

      await saveJPEG(saveFolder, newFilename, 12);

      await revertToSnapshot(newFilename);

      await deleteSnapshot(newFilename);
    }
  });
} catch (error) {
  console.error(error);
  console.trace(error);
}


const { app } = require('photoshop');
const { localFileSystem } = require('uxp').storage;

if (app.documents.length <= 0) { return; }
const doc = app.activeDocument;
const dstEntry = await localFileSystem.getFileForSaving(`${doc.name.replace(/\.[a-z0-9]{2,4}$/i, '')}.png`);
if (dstEntry == null) { return; }

try {
  // entry, PNGSaveOptions, asCopy
  await doc.saveAs.png(dstEntry, { compression: 6 }, true);

  await app.showAlert('Export succeeded.');
} catch (e) {
  await app.showAlert(e);
}

let entry = await require('uxp').storage.localFileSystem.getFileForSaving("target.psd");
document.saveAs.psd(entry);

// Save as a Copy (High JPG quality)
document.saveAs.jpg(entryJpg, { quality: 12 }, true);

// Save a PSB, with some options:
document.saveAs.psb(entryPsb, { embedColorProfile: true });
//compression
document.saveAs.psb(entryPng, { compression: 6 }, true);
_obj: "photoshop35Format"


switch (saveType) {
  case saveType_PNG:

    break;

  default:
    break;
}



async function actionCommands() {
  const result = await batchPlay(
    [
      {
        _obj: "autoMaskGenerate",
        sampleAllLayers: false,
        hardEdge: true,
        _options: {
          dialogOptions: "dontDisplay"
        }
      }
    ],
    {}
  );
}



batchPlay(
  [
    {
      "_obj": "make",
      "_target": { "_ref": "contentLayer" },
      "using": {
        "_obj": "contentLayer",
        "type": {
          "_obj": "solidColorLayer",
          "color": {
            "_obj": "RGBColor",
            "red": 127, "$Grn ": 35,
            "blue": 220
          }
        }
      }
    }
  ], { "synchronousExecution": true })



batchPlay(
  [
    {
      "_obj": "set",
      "_target": {
        _ref: [
          { _property: "targetLayersIDs" },
          { _ref: "document", _enum: "ordinal", _value: "targetEnum" }
        ]
      },
      "to": undefined,
      "_options":
      {
        "dialogOptions": "dontDisplay"
      }
    }],
  { "synchronousExecution": true })

// channel selection

batchPlay(
  [
    {
      "_obj": "rasterizeLayer",
      "_target":
      {
        "_ref": "layer",
        "_enum": "ordinal",
        "_value": "targetEnum"
      },
      "what":
      {
        "_enum": "rasterizeItem",
        "_value": "layerStyle"
      },
      "_options":
      {
        "dialogOptions": "dontDisplay"
      }
    }],
  {
    "synchronousExecution": true
  }
)

batchPlay(
  [
    {
      "_obj": "set",
      "to":
      {
        "_ref": "channel",
        "_enum": "channel",
        "_value": "transparencyEnum"
      },
      "_options":
      {
        "dialogOptions": "dontDisplay"
      }
    }
  ],
  {
    "synchronousExecution": true
  }
)
/*
{ "_ref": "channel", "_enum": "channel", "_value": "transparencyEnum" }

require('photoshop').action.batchPlay(
  [
    { 
      "_obj": "set",
            "_target":
             { "_ref": 
             [
              { "_property": "selection" 
            }, ====
            , "to": 




*/

batchPlay(
  [
    {
      "_obj": "set",
      "_target":
      {
        "_ref":
          [
            {
              "_property": "selection"
            },
          ]
      },
      "to":
      {
        "_ref": "channel",
        "_enum": "channel",
        "_value": "transparencyEnum"
      },
      "_options":
      {
        "dialogOptions": "dontDisplay"
      }
    }
  ],
  {
    "synchronousExecution": true
  }
)



batchPlay(
  [
    {
      _obj: "set",
      _target:
      {
        _ref:
          [
            {
              _property: "selection"
            },
            container.toUXP()
          ]
      }
      ,
      to:
      {
        _ref: "channel",
        _enum: "channel",
        _value: "transparencyEnum"
      },
      _options:
      {
        dialogOptions: "dontDisplay"
      }
    }
  ],
  {
    synchronousExecution: true
  }
)